import React, { useState, useEffect } from 'react'
import { Button, Input, InputNumber, Descriptions, message, Table, Form, Modal, Badge } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { useSelector } from 'react-redux'
import { getLoginUserById, getUserById } from '../../utils/request/get'
import { updateLoginUserById } from '../../utils/request/put'
const { confirm } = Modal

export default function PersonalCenter() {
    const [editingKey, setEditingKey] = useState('')
    const [dataSource, setDataSource] = useState([])
    const [hidden, setHidden] = useState(true)
    const [user, setUser] = useState(null)
    const [form] = Form.useForm()
    const token = useSelector(state => state.TokenReducer.token)

    useEffect(() => {
        async function fetchData() {
            if (token) {
                const { userId } = token
                const res = await getUserById(userId)
                setUser(res.data.user)
                const loginRes = await getLoginUserById(userId)
                setDataSource([loginRes.data.loginUser])
            }
        }
        fetchData()
    }, [token])

    const showConfirm = (type, item) => {
        let obj = {
            icon: <ExclamationCircleOutlined />,
            okText: '确认',
            cancelText: '取消'
        }
        switch (type) {
            case 'CANCEL':
                obj.title = '您确定要取消吗?'
                obj.onOk = function () { setEditingKey('') }
                obj.onCancel = function () { console.log('Cancel'); }
                break
            default: break
        }
        confirm(obj)
    };

    const EditableCell = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }) => {
        const inputNode = inputType === 'number' ? <InputNumber /> : <Input />
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `请输入 ${title}!`,
                            },
                        ]}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        )
    }
    const isEditing = (record) => record.id === editingKey
    const edit = (record) => {
        form.setFieldsValue({
            title: '',
            ...record,
        })
        setEditingKey(record.id)
    }
    const save = async (id) => {
        try {
            const row = await form.validateFields()
            const newData = [...dataSource]
            const index = newData.findIndex((item) => id === item.id)
            if (index > -1) {
                const item = newData[index]
                const newObj = { ...item, ...row }
                newData.splice(index, 1, newObj) // 用 row 这个对象 替换 item
                setDataSource(newData)
                // console.log(newObj);
                updateLoginUserById(id, newObj).then(res => {
                    console.log(res);
                    if (res.data.user.password === newObj.password) {
                        message.success('修改成功')
                    } else {
                        message.error('修改失败')
                    }
                })
                setEditingKey('')
            } else {
                newData.push(row)
                setDataSource(newData)
                setEditingKey('')
            }
        } catch (err) {
            console.log('Validate Failed:', err)
        }
    }

    const columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            width: 100,
        },
        {
            title: '密码',
            dataIndex: 'password',
            key: 'password',
            editable: true,
            render: (password) => {
                return hidden ? (
                    <Button type='primary' onClick={() => { setHidden(false) }}>查看密码</Button>
                ) : (
                    <div>
                        {password}&nbsp;&nbsp;&nbsp;
                        <Button type='primary' onClick={() => { setHidden(true) }}>取消</Button>
                    </div>
                )
            }
        },
        {
            title: '操作',
            width: 200,
            render: (record) => {
                const editable = isEditing(record)
                return editable ? (
                    <span style={{ display: 'flex', justifyContent: 'space-around' }}>
                        <Button
                            onClick={() => save(record.id)}
                            type="primary"
                        >保存</Button>
                        <Button onClick={() => showConfirm("CANCEL")}>取消</Button>
                    </span>
                ) : (
                    <div>
                        <Button disabled={editingKey !== ''} onClick={() => edit(record)}
                            danger>修改密码</Button>
                    </div>
                )
            }
        }
    ];

    const mergedColumns = columns.map((col) => {
        // 若当前不可编辑
        if (!col.editable) {
            return col;
        }
        // 可以编辑
        return {
            ...col,
            onCell: (record) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });

    const getStatus = () => {
        if (user) {
            return user.roleState ? <Badge status='success' text='可用' /> : <Badge status='error' text='禁用' />
        }
    }

    return (
        <div style={{ backgroundColor: 'white', height: '100%', borderRadius: '15px' }}>
            <Descriptions layout="vertical" bordered title={
                <div style={{ margin: '20px 0 0 0px' }}>
                    {user?.username + '的个人信息'}
                </div>
            }>
                <Descriptions.Item label="用户名">{user?.username}</Descriptions.Item>
                <Descriptions.Item label="性别">{user?.gender}</Descriptions.Item>
                <Descriptions.Item label="联系电话">{user?.phoneNumber}</Descriptions.Item>
                <Descriptions.Item label="用户部门">{user?.Department.departmentName}</Descriptions.Item>
                <Descriptions.Item label="用户身份">{user?.Role.roleName}</Descriptions.Item>
                <Descriptions.Item label="账号可用状态">{getStatus()}</Descriptions.Item>
            </Descriptions>
            <div style={{ margin: '20px 0', fontSize: 15, fontWeight: 'bold' }}>
                密码管理</div>
            <Form form={form} component={false}>
                <Table
                    components={{ body: { cell: EditableCell } }}
                    columns={mergedColumns}
                    dataSource={dataSource}
                    rowKey={item => item.id}
                    rowClassName="editable-row"
                    pagination={false}
                />
            </Form>
        </div>
    )
}